﻿package net.wangit;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import net.wangit.context.ActionContext;
import net.wangit.framework.config.GlobalSettings;
import net.wangit.framework.exception.ConfigurationException;
import net.wangit.framework.i18n.LocaleUtil;
import net.wangit.util.Checker;
import net.wangit.util.FileUtil;
import net.wangit.util.PropertiesUtil;
import net.wangit.util.StringUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * 国际化工具类，读取资源文件内容。 资源文件位于{home}/i18n/ 依据Visitor中包含的Locale信息来确定使用哪一个资源文件
 * 
 * @author watson Feb 24, 2010
 */
public class LabelUtil {

	private static final Log log = LogFactory
			.getLog(net.wangit.framework.dispatcher.DispatcherServlet.class);
	private static final String NULL[] = null;
	private static final String DEFAULT_FILE = "app";// 默认资源文件(app)，
	private static final String SUFFIX = ".properties";
	private static Map<String, Properties> resources = new HashMap<String, Properties>();

	// 清除资源文件的缓存。
	public static void clear() {
		resources.clear();
	}

	// 读取默认资源文件(app)，取得指定属性的值。
	public static String get(ActionContext ac, String key) {
		return get(ac, LabelUtil.DEFAULT_FILE, key);
	}

	// 读取指定资源文件，取得指定属性的值。
	public static String get(ActionContext ac, String prefix, String key) {
		int index = key.indexOf(",");
		if (index < 0) {
			return get(ac, prefix, key, NULL);
		} else {
			key = key.substring(0, index);
			String parameters[] = StringUtil.split(key.substring(index + 1),
					",");
			return get(ac, prefix, key, parameters);
		}
	}

	// 读取指定资源文件，取得指定属性的值，并替换其中的参数。
	public static String get(ActionContext ac, String prefix, String key,
			String parameters) {
		return get(ac, prefix, key, StringUtil.split(parameters, ","));
	}

	// 读取指定资源文件，取得指定属性的值，并替换其中的参数。
	public static String get(ActionContext ac, String prefix, String key,
			int parameter) {
		return get(ac, prefix, key, Integer.toString(parameter));
	}

	// 读取指定资源文件，取得指定属性的值，并替换其中的参数。
	public static String get(ActionContext ac, String prefix, String key,
			String parameters[]) {
		String value = getProperties(ac, prefix).getProperty(key);
		if (Checker.isEmpty(value))
			return (new StringBuilder("$L{")).append(prefix).append(":")
					.append(key).append("}").toString();
		if (parameters == null)
			return value;
		for (int i = 0; i < parameters.length; i++) {
			String target = (new StringBuilder("{"))
					.append(Integer.toString(i)).append("}").toString();
			value = StringUtil.replace(value, target, parameters[i]);
		}

		return value;
	}

	private static Properties getProperties(ActionContext ac, String fileName) {
		Visitor visitor = ac.getVisitor();
		String localeString = visitor.getLocaleString();
		String key = (new StringBuilder(String.valueOf(fileName))).append("_")
				.append(localeString).toString();
		Properties props = resources.get(key);
		if (props == null)
			return load(fileName, localeString);
		else
			return props;
	}

	private static Properties load(String prefix, String localeString) {
		String fileName = (new StringBuilder(String.valueOf(prefix))).append(
				"_").append(localeString).toString();
		String path = (new StringBuilder(String.valueOf(Path.getI18nPath())))
				.append(fileName).append(LabelUtil.SUFFIX).toString();
		boolean exists = FileUtil.exists(path);
		if (!exists) {
			String language = GlobalSettings.getLanguage();
			String country = GlobalSettings.getCountry();
			String defaultLocalString = LocaleUtil.getLocaleString(language,
					country);
			if (!Checker.isEmpty(defaultLocalString)) {
				fileName = (new StringBuilder(String.valueOf(prefix))).append(
						"_").append(defaultLocalString).toString();
				path = (new StringBuilder(String.valueOf(Path.getI18nPath())))
						.append(fileName).append(LabelUtil.SUFFIX).toString();
				exists = FileUtil.exists(path);
			}
		}
		if (!exists) {
			fileName = prefix;
			path = (new StringBuilder(String.valueOf(Path.getI18nPath())))
					.append(fileName).append(LabelUtil.SUFFIX).toString();
			exists = FileUtil.exists(path);
		}
		if (!exists) {
			log.error((new StringBuilder("could not load resource: ")).append(
					path).toString());
			throw new ConfigurationException((new StringBuilder(
					"could not load resource: ")).append(path).toString());
		}
		Properties props = resources.get(fileName);
		if (props == null)
			props = PropertiesUtil.getPropertiesByPath(path);
		String key = (new StringBuilder(String.valueOf(prefix))).append("_")
				.append(localeString).toString();
		resources.put(key, props);
		log.info((new StringBuilder("Load resource file: ")).append(path)
				.toString());
		return props;
	}

	private LabelUtil() {
	}

}
